<?php

class Ead_MeuscursosController extends App_Controller_Action
{
    public $dir = 'public/upload/curso/';
    private $_USU_ID;
    
    public function init()
    {
        /* Initialize action controller here */
        $auth = Zend_Auth::getInstance();
        $s_user = $auth->getStorage();
        $this->_USU_ID = $s_user->read()->USU_ID;
    }

    public function indexAction() {
        
        Zend_Loader::loadClass('datetools','library');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/curso.js');
        
        $search = $this->_getParam('inp-search', '');
        $this->view->search = $search;
        
        $hoje = date('Y-m-d');
        $where = 'COMPRA.USU_ID = '. $this->_USU_ID.' AND COMPRA.COM_STATRA like "Completo"';
        $obj = new Ead_Model_DbTable_Compra();
        
        $sql = $obj->select()->setIntegrityCheck(false);
        $sql->from('COMPRA')
            ->join('CURSO','CURSO.CUR_ID = COMPRA.CUR_ID AND ( DATEDIFF("'.$hoje.'",COMPRA.COM_DATPAG) <= CURSO.CUR_QTDDIAACE AND DATEDIFF("'.$hoje.'",COMPRA.COM_DATPAG) >= 0 ) ') 
            ->where($where)->order('COMPRA.COM_DATHOR DESC');
        
        $result = $obj->fetchAll($sql);
        $this->view->result = $this->paginacao($result); 
          
    }
    
    public function conteudoAction(){
        
        $this->view->url_return = $this->_urlbase.'/'.$this->_modulo.'/'.$this->_controller;
        $this->view->a_title = 'Voltar aos cursos';
        
        $cur_id = $this->_getParam('cur_id', 0);

        $this->verificaAcessoCurso($cur_id);

        $this->validaAcessoData($cur_id);
        
        $search = $this->_getParam('inp-search', '');
        $this->view->search = $search;
        $where = 'CUR_ID = '.$cur_id;
        if(strlen($search) > 1){
            $where .= ' and CON_NOM like "%'.$search.'%"';
        }
               
        $obj = new Ead_Model_DbTable_Conteudo();
        $result = $obj->fetchAll($obj->select()->where($where)->order(array('CON_ORD ASC','CON_NOM ASC')));
        $this->view->result = $this->paginacao($result);
        
        $this->view->cur_id = $cur_id;
        
    }
    public function materialAction(){
        
        $cur_id = $this->_getParam('cur_id', 0);
        
        $this->verificaAcessoCurso($cur_id);
        
        $this->validaAcessoData($cur_id);
        
        $this->view->url_return = $this->_urlbase.'/'.$this->_modulo.'/'.$this->_controller.'/conteudo/cur_id/'.$cur_id;
        $this->view->a_title = 'Voltar ao conteúdo';
            
        $id = $this->_getParam('id', 0);
        
        
        Zend_Loader::loadClass('estatisticas','library');
        $obj = new Estatisticas();
        $obj->acesso_pagina($id,1);
        
        if ($id > 0) {
            
            $obj = new Ead_Model_DbTable_Conteudo();
            $row = $obj->fetchRow('CON_ID = ' . $id)->toArray();

            $obj2 = new Ead_Model_DbTable_Repositorio();
            $row2 = $obj2->fetchRow('REP_ID = ' . $row['REP_ID'])->toArray();
         
            $sessao = new Zend_Session_Namespace('Repositorio');
            $sessao->caminho = '..'.$this->_urlbase.'/public/upload/repositorio/';
            $sessao->id = $row2['REP_ID'];
            $sessao->dathor = $row2['REP_DATHOR'];
            //echo $sessao->caminho.md5($sessao->id.$sessao->dathor);
 
        }
    }
    
    public function verificaAcessoCurso($CUR_ID){
        
        $where = 'CUR_ID = '.$CUR_ID.' AND USU_ID = '. $this->_USU_ID.' AND COM_STATRA like "Completo"';
        $obj = new Ead_Model_DbTable_Compra();
        $row = $obj->fetchRow($where);

        try {
            if(!isset($row->CUR_ID) && $row->CUR_ID <= 0 ){
                $this->_helper->redirector('index',$this->_controller,$this->_modulo,array());
            }
        } catch(Exception $ex) {
            $this->_helper->redirector('index',$this->_controller,$this->_modulo,array());
        }
    } 
    
    public function downloadAction(){
        //$this->_helper->layout->disableLayout(); 
        //$this->_helper->viewRenderer->setNoRender();  
        
        $id = $this->_getParam('id');
                
        $obj = new Ead_Model_DbTable_Conteudo();
        $row = $obj->fetchRow('CON_ID = ' . $id);
        
        $rep = $row->findDependentRowSet("Ead_Model_DbTable_Repositorio"); 
        
        $row = $row->toArray();
        
        $aquivoNome = md5($rep[0]['REP_ID'].$rep[0]['REP_DATHOR']).'.*';
        
        $arquivo = 'public/upload/repositorio/'.$aquivoNome; // caminho absoluto do arquivo
        foreach (glob($arquivo) as $src) {
            $arquivo = $src;
        }
   
        if (!file_exists($arquivo)) {
            exit;
        }
        
        $ext = end(explode('.', $arquivo));
        $novoNome = $row['CON_NOM'].'.'.$ext;
        $novoNome = str_replace(' ','',$novoNome);
        $tipo = '';
        
        //$newfile = 'public/upload/temp/'.$novoNome;
        //copy($arquivo, $newfile);
        
        
        /*
        echo "<script>
        window.open('http://neneco.com.br/site/".$newfile."');    
        </script>";
        */
        
        /*
        switch(strtolower(substr(strrchr(basename($arquivo),"."),1))){ // verifica a extensão do arquivo para pegar o tipo
            case "pdf": $tipo="application/pdf"; break;
            case "exe": $tipo="application/octet-stream"; break;
            case "zip": $tipo="application/zip"; break;
            case "doc": $tipo="application/msword"; break;
            case "xls": $tipo="application/vnd.ms-excel"; break;
            case "ppt": $tipo="application/vnd.ms-powerpoint"; break;
            case "gif": $tipo="image/gif"; break;
            case "png": $tipo="image/png"; break;
            case "jpg": $tipo="image/jpg"; break;
            case "mp3": $tipo="audio/mpeg"; break;
        }
        
        //header('Content-Description: File Transfer');
        header('Content-Disposition: attachment; filename="'.$novoNome.'";');
        header('Content-Type: '.$tipo);
        //header('Content-Transfer-Encoding: binary');
        header('Content-Length: ' . filesize($newfile));
        //header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        //header('Pragma: public');
        //header('Expires: 0');
        
        readfile($newfile);
        */
        
        header('Content-Type: image/jpg');
        header('Content-Disposition: attachment; filename="'.$arquivo.'";');
        readfile($arquivo);

        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        
    }
    
    public function validaAcessoData($cur_id = 0){
        $hoje = date('Y-m-d');
        
        if($cur_id <= 0){
            $this->_helper->redirector('index','meuscursos',$this->_modulo,array());
        }
        
        $hoje = date('Y-m-d');
        $where = 'COMPRA.USU_ID = '. $this->_USU_ID.' AND COMPRA.CUR_ID = '. $cur_id .' AND COMPRA.COM_STATRA like "Completo"';
        $obj = new Ead_Model_DbTable_Compra();
        
        $sql = $obj->select()->setIntegrityCheck(false);
        $sql->from('COMPRA')
            ->join('CURSO','CURSO.CUR_ID = COMPRA.CUR_ID AND ( DATEDIFF("'.$hoje.'", COMPRA.COM_DATPAG) <= CURSO.CUR_QTDDIAACE AND DATEDIFF("'.$hoje.'", COMPRA.COM_DATPAG) >= 0 ) ')
            ->where($where)->order('COMPRA.COM_DATHOR DESC');
        
        $row = $obj->fetchRow($sql);
        
        if($row->CUR_ID <= 0){
            $this->_helper->redirector('index','meuscursos',$this->_modulo,array());
        }
         
         
    }

}

